﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using Odyssey.Utils;
using System.Linq;

namespace Odyssey.Behaviors
{
    /// <summary>
    /// Advances the focus to the next TextBox or PasswordBox when the Enter key is pressed.
    /// </summary>
    public class EnterNavigationBehavior : Behavior<Panel>
    {
        protected override void OnAttached()
        {
            AssociatedObject.KeyUp += new KeyEventHandler(OnKeyUp);
            base.OnAttached();
        }

        protected override void OnDetaching()
        {
            AssociatedObject.KeyUp -= OnKeyUp;
            base.OnDetaching();
        }

        void OnKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                FrameworkElement focused = FocusManager.GetFocusedElement() as FrameworkElement;
                TextBox tb = focused as TextBox;
                if (tb == null || !tb.AcceptsReturn)
                {
                    var siblings = focused.GetVisualSiblingsAndSelf().ToArray();
                    int index = Array.IndexOf(siblings, focused);
                    int count = siblings.Length;
                    index++;
                    Control next = null;
                    while (index < count && next == null)
                    {
                        next = siblings[index].GetVisualDescendantsAndSelf().OfType<Control>().FirstOrDefault(c => (c is TextBox) || (c is PasswordBox));
                        if (next != null)
                        {
                            next.Focus();
                        }
                        else index++;
                    }
                }
            }
        }
    }
}
